<?php
class orderModel
{
    public function __construct(& $base)
    {
        $this->base = $base;
        $this->base->in_erpDb();
        $this->redis = &$this->base->redis;
    }

    /**
     * 生成订单
     * @param $data
     * @return mixed
     */
    public function addOrder($data){
        $order_id = $this->createOrderSn();
        $data['order_id'] = $order_id;
        $data['client_type'] = isset($data['client_type']) ? $data['client_type']: common::getOs();
        $data['updatetime'] = $data['addtime'] = time();
        $this->base->load('goods')->updateNum($data['goods_id'],$data['num']);//减少商品数量
        $this->base->erpDb->query("update r_goods set buy_num = buy_num+{$data['num']} where id = '{$data['goods_id']}'");//更新商品购买数量
        $this->base->erpDb->insertRowTable('r_order',$data);
        return $order_id;
    }

    /**
     * 获取订单详情
     * @param $orderId
     * @return array
     */
    public function getOrderDetail($uid,$orderId){
        $orderInfo = $this->base->erpDb->getRow("select * from r_order where uid='$uid' and order_id = '$orderId'");
        if(empty($orderInfo)){
            return [];
        }
        $shippingStatus = 1;
        $goodsList = [];
        $price = 0;
        $isGoods = 1;
        $shippingNum = 0;
        $shippingName = '';
        $shippingCode = '';
        $thumb = '';
        $subTitle = '';
        $name = '';
        $cost = 0;
        $isClaim = 0;
        $goods_desc = '';
        $price_desc = '';
        $is_virtual = 0;
        $discountInfo = [];
        $discount = 1;
        $actInfo = [];
        if($orderInfo['match_id']){
            //赛事
            $actInfo = $this->base->load('match')->getMatchInfo($orderInfo['match_id']);
            $discountInfo = $actInfo['discount'];
            $goods = json_decode($orderInfo['goods'],true);
            $goods_mod = $this->base->load('goods');
            $goods_num = 0;
            foreach($goods as $_goods){
                if($_goods['id'] == $actInfo['fee_goods_id']){
                    $cost = $_goods['price'];
                    continue;
                }
                $goodsInfo = $goods_mod->getRaceGoodsInfo($_goods['id']);
                if(empty($goodsInfo)){
                    continue;
                }
                $goodsInfo['goodsInfo'] = array_merge($_goods,$goodsInfo['goodsInfo']);
                $goodsList[] = $goodsInfo;
                $goods_num++;
                $price += $_goods['price']*$_goods['num'];
                if($goodsInfo['product']['is_virtual']){
                    $is_virtual = 1;
                }
            }
            $_price = $price;
            $_last_num = 0;
            foreach($discountInfo as $row){
                if($goods_num >= $row['num'] && $row['num'] > $_last_num){
                    $discount = $row['discount'];
                    $_price = $price*$discount;
                    $_last_num = $row['num'];
                }
            }
            $price_desc = $this->makePriceDesc($cost,$price,$discount);
            $price = $_price;
            $isGoods = $is_virtual ? 0 : 1;
            $name = $actInfo['name'];
        } else if ($orderInfo['act_id'] && $orderInfo['act_type'] == 2) {
            //马拉松
            $actInfo = $this->base->load('marathon')->getMarathonInfo($orderInfo['act_id'], ['title', 'start_time', 'end_time']);
            $actInfo['stime'] = $actInfo['start_time'];
            $actInfo['etime'] = $actInfo['end_time'];
            $goods = json_decode($orderInfo['goods'],true);
            $goodsInfo = $this->base->load('goods')->getGoodsById($goods[0]['id']);
            $isGoods = $goodsInfo['is_virtual'] ? 0 : 1;
            $name = $actInfo['title'];
        }elseif($orderInfo['act_type'] == 5 || $orderInfo['act_type'] == 8){
            $goods = json_decode($orderInfo['goods'],true);
            $goods_mod = $this->base->load('goods');
            $goods_num = 0;
            foreach($goods as $_goods){
                $goodsInfo = $goods_mod->getRaceGoodsInfo($_goods['id']);
                if(empty($goodsInfo)){
                    continue;
                }
                $goodsInfo['goodsInfo'] = array_merge($_goods,$goodsInfo['goodsInfo']);
                $goodsList[] = $goodsInfo;
                $goods_num++;
                $price += $_goods['price']*$_goods['num'];
                if($goodsInfo['product']['is_virtual']){
                    $is_virtual = 1;
                }
            }
            $_price = $price;
            $name = '闪购';
        } else if($orderInfo['act_type'] == 6) {
            $goods = json_decode($orderInfo['goods'],true);
            $live_mod = $this->base->load('live/live');
            $goods_num = 0;
            $liveId = 0;
            foreach($goods as $_goods){
                $liveInfo = $live_mod->getLiveInfo($_goods['id'], 'title, image_url, price');
                if(empty($liveInfo)){
                    continue;
                }
                $liveId = $_goods['id'];
                $goodsInfo = array(
                    'product'=>[
                        'id'=>0,
                        'code'=>'',
                        'title'=>$liveInfo['title'],
                        'is_virtual'=>1,
                        'imageCnt'=>1,
                        'imageList'=>[$liveInfo['image_url']]
                    ],
                    'goodsInfo'=>[
                        'attrPathName'=>'报名费',
                        'stockNum'=>0,
                        'saleNum'=>0,
                        'saleprice'=>$liveInfo['price'],
                        'erpRealStockNum'=>0,
                        'erpGoodId'=>0,
                    ]
                );
                $goodsInfo['goodsInfo'] = array_merge($_goods,$goodsInfo['goodsInfo']);
                $goodsList[] = $goodsInfo;
                $goods_num++;
                $price += $_goods['price']*$_goods['num'];
            }
            $_price = $price;
            $is_virtual = 1;
            $isGoods = $is_virtual ? 0 : 1;
            $name = '微课报名';
        }elseif($orderInfo['aid']){
            //群组活动
            $actInfo = $this->base->load('groupActivity')->getActByAid($orderInfo['aid']);
            $goodsInfo = $this->base->load('goods')->getGoodsById($orderInfo['goods_id']);
            if(!empty($actInfo)){
                $thumb = $actInfo['img'];
                $name = $actInfo['title'];
                $subTitle = isset($actInfo['short_desc']) ? $actInfo['short_desc'] : '';
                $cost = $this->redis->hget(REDIS_PREFIX.'ActivityInfo_'.$orderInfo['aid'],'cost');
            }
            if(!empty($goodsInfo)){
                $thumb = $goodsInfo['thumb'];
                $name = $goodsInfo['goods_name'];
                $subTitle =  $this->redis->hget(REDIS_PREFIX."GroupInfo_".$orderInfo['gid'],'name');
                $subTitle = empty($subTitle) ? '' : $subTitle;
                $price = $goodsInfo['price'];
            }
            $isClaim = intval($this->redis->sismember(REDIS_PREFIX."ACTaccept_".$orderInfo['aid'],$orderInfo['gid']));
            
            $goodsId = $orderInfo['goods_id'];
            if($goodsId > 0 && isset($actInfo['gift_type']) && $actInfo['gift_type'] == 2){
                $isGoods = 1;
            }else{
                $isGoods = 0;
            }
        }
        
        if($orderInfo['shipping_id'] > 0){
            $shippingStatus = $this->base->erpDb->getOne("select shipping_status from r_order_action where order_id = '{$orderId}'");
        }
        if($orderInfo['consignee_id'] == 0){
            $consigneeInfo = $this->base->db->getRow("select name,phone from r_collect_info where uid='$uid' order by id desc");
            if (!$consigneeInfo) {
                $nickname = $this->redis->hget(REDIS_PREFIX . 'UserInfo_' . $uid, 'nickname');
                $phone = $this->redis->hget(REDIS_PREFIX . 'UserInfo_' . $uid, 'phone');
                $consigneeInfo['name'] = $nickname ? $nickname : '';
                $consigneeInfo['phone'] = $phone ? $phone : '';
            }
            $consigneeInfo['id'] = $consigneeInfo['province'] = $consigneeInfo['city'] = $consigneeInfo['district'] = $consigneeInfo['address'] = $consigneeInfo['is_default'] = '';
        }else{
            $consigneeInfo = $this->getConsigneeById($orderInfo['consignee_id']);
        }
        if($orderInfo['status'] == 2 || $orderInfo['status'] == 4){
            $shippingNum = $this->base->erpDb->getOne("select shipping_num from r_order_action where order_id={$orderId}");
        }
        if($orderInfo['shipping_id'] > 0){
            $shippingInfo = $this->base->load('adminErp')->getlogisticsTepInfo($orderInfo['shipping_id'],'title');
            if(!empty($shippingInfo)){
                //$shippingCode = $shippingInfo['shipping_code'];
                $shippingName = $shippingInfo['title'];
            }

        }
        $reData = [
            'name'          => $consigneeInfo['name'],
            'phone'         => $consigneeInfo['phone'],
            'address'       => isset($consigneeInfo['province']) ? $consigneeInfo['province'].$consigneeInfo['city'].$consigneeInfo['district'].$consigneeInfo['address'] : "",
            'thumb'         => $thumb,//图片
            'goods_name'    => $name, //名称
            'subTitle'      => $subTitle, //副标题
            'shipping_fee'  => $orderInfo['shipping_fee'],//配送费
            'total_fee'     => $orderInfo['total_fee'], //总费用
            'pay_status'    => $orderInfo['pay_status'], //支付状态
            'status'        => $orderInfo['status'], //订单状态
            'order_id'      => $orderId, //订单号
            'mark'          => empty($orderInfo['mark']) ? '' : $orderInfo['mark'], //备注
            'addtime'       => date('Y.m.d H:i:s',$orderInfo['addtime']), //下单时间
            'expireTime'    => $orderInfo['expireTime'],
            'price'         => $price,
            'cost'          => $cost,
            'num'           => $orderInfo['num'], //购买数量
            'stime'         => isset($actInfo['stime']) ? $actInfo['stime'] : 0, //活动开始时间
            'etime'         => isset($actInfo['etime']) ? $actInfo['etime'] : 0, //活动结束时间
            'goodsType'     => $isGoods, //是否有商品
            'shipping_num'  => empty($shippingNum) ? '' : $shippingNum, //快递单号
            'shipping_code' => $shippingCode, //快递编码
            'shipping_name' => $shippingName, //快递名称
            'shStatus'      => $shippingStatus,
            'updatetime'    => date("Y.m.d H:i:s",$orderInfo['paytime']), //更新时间
            'gid'           => $orderInfo['gid'],
            'aid'           => $orderInfo['aid'],
            'isClaim'       => $isClaim,
            'match_id'      => $orderInfo['match_id'],
            'act_id'        => $orderInfo['act_id'],
            'act_type'      => $orderInfo['act_type'],
            'goodsList'     => $goodsList,
            'actInfo'       => (object)$actInfo,
            'discount'      => $orderInfo['discount'],
            'price_desc'    => $price_desc,
            'is_virtual'    => $is_virtual
        ];
        return $reData;
    }
    
    /*
     * 获取用户订单数
     * @param $uid
     * @param int $status 1：待付款  2：已发货  0：全部
     */
    public function getCountOrderByUid($uid,$status=0){
        $sql = "select count(1) from r_order o left join `hupu_jog`.`r_group_activity` ga on ga.aid=o.aid where o.uid='$uid'";
        $where_ext = "";
        switch($status){
            case 1:
                $time = time();
                $where_ext .= " and pay_status=10 and ga.stime > {$time}";
                break;
            case 2:
                $where_ext .= " and o.status=2";
                break;
        }
        $where_ext .= " AND o.aid != 0";
        $sql .= $where_ext;
        return $this->base->erpDb->getOne($sql);
    }

    /**
     * 通过UID获取用户的订单信息
     * @param $uid
     * @param int $status 1：待付款  2：已发货  0：全部
     * @return array
     */
    public function getOrderByUid($uid,$status=0){
        $sql = "select o.order_id from r_order o";
        $arrActType = [1,5,8];
        if($this->base->afterVersion('2.9.1', '2.9.1')) {
            $arrActType[] = 6;
        }
        $strActType = implode(',', $arrActType);
        $where = " where o.uid='$uid' and o.`act_type` in ($strActType) AND o.act_id !=0";
        switch($status){
            case 1:
                $time = time();
                $where .= " and pay_status=10 and o.status=1";
                break;
            case 2:
                $where .= " and o.status=2";
                break;
        }
        $order = ' order by o.order_id desc';
        $orders = $this->base->erpDb->getAll($sql.$where.$order);
        if(empty($orders)){
            return [];
        }
        $reData = [];
        $isGoods = 0;
        $now = time();
        $goods_mod = $this->base->load('goods');
        foreach($orders as $item){
            $orderInfo = $this->getOrderDetail($uid,$item['order_id']);
            if($orderInfo && ($orderInfo['act_type']== 6) && ($orderInfo['pay_status'] <> 20)) {
                continue;
            }
            $orderInfo['cur_time'] = $now;
            $orderInfo['goods_name'] = '';
            $orderInfo['subTitle'] = '';
            $orderInfo['thumb'] = '';
            $orderInfo['isGoods'] = $orderInfo['goodsType'];
            $reData[] = $orderInfo;
        }
        return $reData;

    }

    /**
     * 获取收货人信息
     * @param $id
     * @return mixed
     */
    public function getConsigneeById($id){
        return $this->base->erpDb->getRow("select * from r_consignee where id='$id'");
    }

    /**
     * 通过ID获取配送信息
     * @param $id
     * @return mixed
     */
    public function getShippingById($id){
        return $this->base->erpDb->getRow("select * from r_shipping where id='$id' and is_show=1");
    }

    /**
     * 获取配送信息
     * @param mixed $fields 字段，多个字段用数组表示
     * @return array
     */
    public function getShippingList($fields="*"){
        if(is_array($fields)){
            $fields = implode(',',$fields);
        }
        return $this->base->erpDb->getAll("select $fields from r_shipping where is_show=1");
    }

    /**
     * 生成18位订单号
     * @return string
     */
    public function createOrderSn(){
        return date('YmdHis').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 4);
    }

    /**
     * 通过活动ID获取用户的订单信息
     * @param $uid
     * @param $aid
     * @return mixed
     */
    public function getOrderByAid($uid,$aid){
        $sql = "select * from r_order where uid='$uid' and aid='$aid' and status!=3";
        return $this->base->erpDb->getRow($sql);
    }

    public function getOrderByOrderId($orderId){
        $sql = "select * from r_order where order_id ='$orderId' and status!=3";
        return $this->base->erpDb->getRow($sql);
    }

    /**
     * 查询用户未取消的商品订单数量 通过订单类型
     * @param $uid
     * @param $actId    活动ID
     * @param $actType  活动类型 0:群组活动,1:赛事,2:马拉松 5 闪购
     * @return mixed
     */
    public function getOrderNumByActId($uid,$actId,$actType){
        $sql = "select count(1) as cnt from r_order where uid=$uid and act_type=$actType and act_id=$actId  and status!=3";
        return $this->base->erpDb->getOne($sql);
    }

    public function getNoPayOrderNum($uid,$actType){
        $where = "uid=$uid and act_type=$actType and status=1 and pay_status=10";
        $sql = "select count(1) as cnt from r_order where $where";
        return $this->base->erpDb->getOne($sql);
    }

    public function getShippingName($shippingCode){
        $name = $this->base->erpDb->getOne("select shipping_name from r_shipping where shipping_code = '{$shippingCode}'");
        return empty($name) ? "" : $name;
    }
    
    /**
     * 条件获取最新一条订单记录
     * @param array $field 获得的字段
     * @param string $where 条件字符串
     * 
     * @return record 查询结果集
     */
    public function getOrderByCond($field = [], $where = '1') {
        $field = empty($field) ? '*' : implode(',', $field);
        $sql = 'select ' . $field . '  from r_order where ' . $where . ' order by id desc limit 1';
        return $this->base->erpDb->getRow($sql);  
    }
    
    /*
     * 获得收货人列表
     */
    public function getConsigneeList($uid){
        $this->base->in_erpDb();
        $list = $this->base->erpDb->getAll("select * from r_consignee where uid = '$uid' and status=0 order by is_default desc");
        $data = [];
        foreach($list as $key=>$info){
            $data[$key] = [
                'id'         => $info['id'],
                'name'       => $info['name'],
                'province'   => $info['province'],
                'city'       => $info['city'],
                'district'   => $info['district'],
                'address'    => $info['address'],
                'phone'      => $info['phone'],
                'is_default' => $info['is_default']
            ];
        }
        return $data;
    }
    
    /*
     * 添加赛事订单
     */
    public function addMatchOrder($data){
        $order_id = $this->createOrderSn();
        $data['client_type'] = isset($data['client_type']) ? $data['client_type']: common::getOs();
        $data['updatetime'] = $data['addtime'] = time();
        //goods
        if(!is_array($data['goods'])){
            throw new Exception(101);
            return false;
        }
        
        //todo 商品数量减少
        $data['act_type'] = '1';
        $data['act_id'] = $data['match_id'];
        $data['goods'] = json_encode($data['goods']);
        $data['order_id'] = $order_id;
        $this->base->erpDb->insertRowTable('r_order',$data);
        return $order_id;
    }
    
    /*
     * 获得赛事订单详情
     * 废弃 by ljj
     * 当orderInfo 可为 order_id
     */
    public function getMatchOrderInfo($uid,$orderInfo,$with_goods=false){
        //当orderInfo is order_id
        if(is_numeric($orderInfo)){
            $sql = "select * from r_order where uid={$uid} AND order_id='{$orderInfo}'";
            $orderInfo = $this->base->erpDb->getRow($sql);
        }
        
        if(!$orderInfo){
            return false;
        }
        
        $orderInfo['goodsList'] = [];
        if($with_goods){
            $goods = json_decode($orderInfo['goods'],true);
            $goods_mod = $this->base->load('goods');
            foreach($goods as $goodsInfo){
                $_goods = $goods_mod->getGoodsById($goodsInfo['id']);
                if(!$_goods){
                    continue;
                }
                $_goods['price'] = $goodsInfo['price'];
                $_goods['num'] = $goodsInfo['num'];
                $orderInfo['goodsList'][] = $_goods;
            }
        }
        return $orderInfo;
    }
    
    /**
     * 生成马拉松活动相关订单
     * @param $data
     * @return mixed
     */
    public function addMarahonOrder($data){
        $order_id = $this->createOrderSn();
        $data['order_id'] = $order_id;
        $data['client_type'] = isset($data['client_type']) ? $data['client_type']: common::getOs();
        $data['updatetime'] = $data['addtime'] = time();
        $goods_mod = $this->base->load('goods');
        foreach($data['goods'] as &$goods){
            $goodsInfo = $goods_mod->getGoodsById($goods['id']);
            $goods['price'] = $goodsInfo['price'];
            if($this->base->erpDb->getOne("select num from r_goods where id={$goodsInfo['id']}")<$goods['num']){
                throw new Exception(3001);
                return;
            }
        }
        foreach($data['goods'] as $goods){
            $goods_mod->buyGoods($goods['id'],$goods['num']);
        }
        $data['goods'] = json_encode($data['goods']);
        //马拉松订单类型
        $data['act_id'] = $data['aid'];
        $data['act_type'] = 2;
        unset($data['aid']);
        $this->base->erpDb->insertRowTable('r_order',$data);
        return $order_id;
    }

    /**
     * 生成闪购订单
     * @param $data
     * @return mixed
     */
    public function addFlashSalesOrder($data){
        $order_id = $this->createOrderSn();
        $data['order_id'] = $order_id;
        $data['client_type'] = isset($data['client_type']) ? $data['client_type']: common::getOs();
        $data['updatetime'] = $data['addtime'] = time();
        if(!is_array($data['goods'])){
            throw new Exception(101);
            return false;
        }
        $arrGoods = $data['goods'];
        $data['goods'] = json_encode($data['goods']);
        //闪购订单类型
        $data['act_type'] = 5;
        $data['act_id'] = $data['aid'];

        $flashInfo = $this->base->load('flashBuy')->getFlashBuyInfo($data['aid']);
        //海淘订单类型更改
        if($flashInfo['type']==4) {
            $data['act_type'] = 8;
        }

        unset($data['aid']);
        $id = $this->base->erpDb->insertRowTable('r_order',$data);
        if ($id) {
            $goods_mod = $this->base->load('goods');
            foreach($arrGoods as $goods){
                $goods_mod->saleFlashGoods($goods['id'], $goods['num']);
            }
        }
        return $order_id;
    }

    /**
     * 生成微课订单
     * @param $data
     * $param $type 1:报名 2：充值
     * @return mixed
     */
    public function addLiveOrder($data, $atype='liveSignUp'){
        $order_id = $this->createOrderSn();
        $data['order_id'] = $order_id;
        $data['client_type'] = isset($data['client_type']) ? $data['client_type']: common::getOs();
        $data['updatetime'] = $data['addtime'] = time();
        if(!is_array($data['goods']) || !in_array($atype, array('liveSignUp', 'liveTopUp'))){
            throw new Exception(101);
            return false;
        }
        $arrGoods = $data['goods'];
        $data['goods'] = json_encode($data['goods']);
        //订单类型
        $data['act_type'] = $atype == 'liveSignUp' ? 6 : 7;
        $data['act_id'] = $data['aid'];
        unset($data['aid']);
        if($atype == 'liveTopUp') {//充值
            $goldConfiguration = common::$goldConfiguration;
            $data['gold_num'] = $goldConfiguration[$data['act_id']]['goldNum'];
            $data['give_gold_num'] = $goldConfiguration[$data['act_id']]['giveNum'];
        }
        $id = $this->base->erpDb->insertRowTable('r_order',$data);
        if ($id) {//预留：以后有需要对聊天室人数进行限制的时候，要先扣除数量
        }
        return $order_id;
    }

    /**
     * 查询待发货订单信息
     */
    public function getOrderListForWaitSend() {
        $list = $this->_getOrderListForWaitSend('order_id,name,phone,province,city,district,address,goods,mark,act_type,act_id,uid');
        if (!$list) return false;
        $result =[];
        foreach ($list as $key=>$val) {
            $result[$key]['ordersn'] = $val['order_id'];
            $result[$key]['name']    = $val['name'];
            $result[$key]['phone']   = $val['phone'];
            $result[$key]['address'] = $val['province'].' '.$val['city'].' '.$val['district'].' '.$val['address'];
            $result[$key]['ordersn'] = $val['order_id'];//货品名称 货品规格
            $result[$key]['mark']    = $val['mark'];
            $result[$key]['act_type'] = $val['act_type'];
            $result[$key]['act_id'] = $val['act_id'];
            $result[$key]['uid'] = $val['uid'];
            $goodsList = [];
            if (!$val['goods'] || !$goods = json_decode($val['goods'],true)) {
                $result[$key]['strGoodsList'] = '';continue;
            }
            $goods_mod = $this->base->load('goods');
            foreach($goods as $goodsInfo){
                $_goods = $goods_mod->getRaceGoodsInfo($goodsInfo['id']);
                if(!$_goods){
                    continue;
                }
                $_goods['goodsInfo'] = array_merge($goodsInfo,$_goods['goodsInfo']);
                $strGoods = '';
                $strGoods .= $_goods['product']['title'];
                $strGoods .= ' | '.$_goods['goodsInfo']['attrPathName'];
                $strGoods .= ' | '.$_goods['goodsInfo']['num'];
                $strGoods .= ' | '.$_goods['goodsInfo']['price'];
                $strGoods .= ' | '.$_goods['goodsInfo']['num']*$_goods['goodsInfo']['price'];
                $goodsList[] = $strGoods;
            }
            if (!$goodsList) {
                $result[$key]['strGoodsList'] = '';continue;
            }
            $result[$key]['strGoodsList'] = implode("\n",$goodsList);
        }
        return $result;
    }

    /**
     * 查询待发货订单(赛事/闪购)
     */
    public function _getOrderListForWaitSend($fields='*') {
        $sql = "select $fields
                 from r_order
                 where status=1
                 and pay_status=20";
        return  $this->base->erpDb->getAll($sql);
    }

    /**
     * 查询订单
     */
    public function getRaceOrderInfoForWaitSend($orderId) {
        $sql = "select * from r_order where order_id ='$orderId'";
        return $this->base->erpDb->getRow($sql);
    }

    /*
     * 发货
     */
    public function addOrderAction($data){
        extract($data);
        $row = compact('id','order_id','shipping_id','shipping_status','shipping_num','uid');
        !isset($data['id']) && $row['addtime'] = time();
        $this->base->erpDb->updateRowTable('r_order_action',$row);
    }
    
    /*
     * 完成订单
     */
    public function finishOrder($match_id,$uid){
        $status = 4;
        $this->base->erpDb->updateRowTable('r_order',compact('match_id','uid','status'));
    }
    
    /*
     * 生成价格算式
     */
    public function makePriceDesc($cost,$price,$discount){
        if(!$cost || !$price){
            return '';
        }
        return $discount == 1 ? "$cost + $price" : "$cost + ($price x $discount)";
    }

    /**
     * 更新充值结果
     */
    public function setAddGoldStatus($id) {
        $this->base->erpDb->update("update r_order set add_gold_status=1 where id=$id");
    }

    /**
     * 添加海淘订单
     */
    public function createHaitaoOrder($orderInfo){
        print_r($orderInfo);
        $good = current(json_decode($orderInfo['goods']));
        $sql = "select  code from r_goods where id = (select stand_good_id from r_object_goods where id =".$good->id.")";
        $str = $this->base->in_db('erpManageDb')->getOne($sql);
        $arr = explode("_",$str);
        $product = [array(
            'goods_id'=>$arr[1],
            'sku_id'=>$arr[2],
            'number'=>$good->num)];
        $address = array('name'=>$orderInfo['name'],
            'postcode'=>'100000',
            'province'=>$orderInfo['province'],
            'city'=>$orderInfo['city'],
            'area'=>$orderInfo['district'],
            'mobile'=>$orderInfo['phone'],
            'street'=>$orderInfo['address']
        );
        $user = $this->base->load('user')->getUserInfo($orderInfo['uid']);
        $result = $this->base->load('shihuo')->createOrder($orderInfo, $product, $address, $user);
        if($result) {
            return $this->base->erpDb->insertRowTable('r_order_haitao', array(
                'order_id' => $orderInfo['order_id'],
                'main_orderno' => $result['main_order'],
                'child_orderno' => $result['child_order']
            ));
        }
    }

    /**
     * 更新海淘订单状态
     */

    public function updateHaitaoOrderStatus($orderinfo){
        $status = $orderinfo->status;
        $status_txt = $orderinfo->status_txt;
        $remark = $orderinfo->refund_remark;
        $child_orderno = $orderinfo->order_id;

        $sql = "update r_order_haitao set status=$status,status_txt='$status_txt',remark='$remark' where child_orderno=$child_orderno";
        return $this->base->erpDb->update($sql);
    }

}